#!/bin/bash

PATH_CWD=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
#echo $PATH_CWD

source $PATH_CWD/.envsetup
source $PATH_CWD/.testsuite

rm -rf $PATH_OUT
mkdir -p $PATH_OUT

rm -f $PATH_OUT_IMAGE
echo "$PATH_OUT_IMAGE is removed!"
echo ""

PATH_OUT_ROOT=$PATH_OUT/rootfs
mkdir -p $PATH_OUT_ROOT

# rootfs layout
# /
# ├── bin
# ├── dev
# ├── etc
# ├── proc
# ├── sbin
# ├── sys
# ├── usr
# └── linuxrc

cd $PATH_OUT_ROOT

cp -r $PATH_BUSYBOX/bin . \
&& cp -r $PATH_BUSYBOX/sbin . \
&& cp -r $PATH_BUSYBOX/usr . \
&& cp -r $PATH_BUSYBOX/linuxrc . \
&& mkdir -p dev \
&& mkdir -p proc \
&& mkdir -p sys \
&& mkdir -p etc \
&& mkdir -p etc/init.d \
&& touch ./etc/init.d/rcS \
&& chmod +x ./etc/init.d/rcS

cat > ./etc/init.d/rcS <<EOF
#!/bin/sh
mount -t proc none /proc
mount -t sysfs none /sys
/sbin/mdev -s
EOF

# import test suite here
source $TESTSUITE

# exit rootfs folder
cd $PATH_OUT

# Create the rootfs image without sudo.
mke2fs \
  -d "$PATH_OUT_ROOT" \
  -t ext4 \
  "$PATH_OUT_IMAGE" \
  1g

# remove rootfs folder
rm -rf $PATH_OUT_ROOT

echo "$PATH_OUT_IMAGE is created!"
